package com.zhang.crawler.utils;


import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Copyright:   Copyright 2007 - 2017 MPR Tech. Co. Ltd. All Rights Reserved.
 * Date:        2017年09月06日 上午10:13
 * Author:      cncbox
 * Version:     1.0.0.0
 * Description: 分页参数类
 */

/**
 * 分页参数类
 */
@ApiModel(value = "分页参数类")
public class PaginationParameter extends BaseObject {


    /**
     * 单页数据量
     */
    @ApiModelProperty(value = "单页数据量",example = "10")
    private Integer pageRows;

    /**
     * 当前数据页码
     */
    @ApiModelProperty(value = "当前数据页码",example = "1")
    private Integer pageIndex;

    /**
     * 目前不考虑字段排序,默认为null
     */
    private String pageOrder;

    /**
     * 数据总量
     */
    private Long pageDataSize;

    /*
    * token
    * */
    private String token;

    public Integer getPageRows() {
        return pageRows == null || pageRows < 1 ? (pageRows = 10) : pageRows;
    }

    public void setPageRows(Integer pageRows) {
        this.pageRows = pageRows;
    }


    public Integer getPageIndex() {
        return pageIndex == null || pageIndex < 1 ? (pageIndex = 1)
                : pageIndex;
    }

    public void setPageIndex(Integer pageIndex) {
        this.pageIndex = pageIndex;
    }

    public String getPageOrder() {
        return pageOrder;
    }

    public void setPageOrder(String pageOrder) {
        this.pageOrder = pageOrder;
    }

    public Long getPageDataSize() {
        return pageDataSize;
    }

    public void setPageDataSize(Long pageDataSize) {
        if (pageDataSize == null || pageDataSize < 1) {
            this.pageDataSize = 0l;
        } else {
            this.pageDataSize = pageDataSize;
        }
    }

    public Integer getPageDataStart() {
        return (getPageIndex() - 1) * getPageRows();
    }

    public Integer getPageDataEnd() {
        return getPageDataStart() + getPageRows() - 1;
    }

    public Map<String, String> getPageOrders() {
        return getOrders(pageOrder);
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    private static Map<String, String> getOrders(String pageOrder) {
        Map<String, String> orderMap = null;
        if (StringUtils.isNotBlank(pageOrder)) {
            String[] split = pageOrder.split(";");
            orderMap = new LinkedHashMap<>(split.length);
            for (String orderStr : split) {
                String[] split1 = orderStr.split(":");
                orderMap.put(split1[0], split1.length > 1 ? split1[1] : "0");
            }
        }
        return orderMap;
    }

}
